<?php

namespace App\Logic;

use \Common\Logic\BaseLogic;

class UserLogic extends BaseLogic
{
    private $userModel;
    private $incomeModel;
    private $withdrawalModel;
    private $questionModel;


    public function __construct()
    {
        parent::__construct();
        $this->userModel = D('User');
        $this->incomeModel = D('Income');
        $this->withdrawalModel = D('Withdrawal');
        $this->questionModel = D('Question');
    }

    /**
     * 根据条件统计
     * @param array $where
     * @return mixed
     */
    public function statistics($where = array())
    {
        return $this->userModel->where($where)->count();
    }

    /**
     * 获取单条join
     * @param $where
     * @return mixed
     */
    public function findUserInfo($where)
    {
        $info = $this->userModel->where($where)->find();
        return static::$res->suc("成功", $info);
    }


    /**
     * 获取参与列表
     * @param int $page
     * @param int $size
     * @param array $where
     * @return mixed
     */
    public function getUserList($page = 1, $size = 20, $where = array())
    {
        $list = $this->userModel->where($where)->page($page . "," . $size)->order('id desc')->select();
        $count = $this->statistics($where);

        return static::$res->suc("成功", array(
            "list" => $list,
            "count" => $count
        ));
    }

    /**
     * 获取用户余额
     * @param $userId
     * @return mixed
     */
    public function getBlanceInfo($userId)
    {
        if (empty($userId)) {
            return static::$res->err("用户ID不能为空");
        }

        //获取用户所有的收益
        $income = $this->incomeModel->where(array(
            "user_id" => $userId
        ))->sum('income');

        //获取用户所有的取现
        $withdrawal = $this->withdrawalModel->where(array(
            "user_id" => $userId,
            "state" => array('neq', 3)
        ))->sum('sum');

        $blance = $income - $withdrawal;
        $blanceInfo = array(
            "income" => $income,
            "withdrawal" => $withdrawal,
            "blance" => $blance
        );
        return static::$res->suc("成功", $blanceInfo);
    }

    /**
     * 获取问题列表
     * @return mixed
     */
    public function getQuesList()
    {
        $where = array(
            "state" => 1
        );
        $list = $this->questionModel->where($where)->field("title,ask")->order('order_id desc')->select();
        return $list;
    }


}
